package com.ichoice.rabbitmq.rpc.helper.util;

import cn.hutool.core.thread.NamedThreadFactory;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author xianrensawang
 * @date 2021/3/26
 */
public final class ExecutorUtils {

    private ExecutorUtils(){

    }

    public static ThreadPoolTaskExecutor createPool(String threadName) {
        // 拿到当前服务器的cpu处理器个数, 设置为核心线程数
        int coreSize = Runtime.getRuntime().availableProcessors();
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(coreSize/2);
        taskExecutor.setMaxPoolSize(coreSize);
        taskExecutor.setKeepAliveSeconds(60);
        taskExecutor.setQueueCapacity((int) (coreSize / 0.4 / 0.1));
        // CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        taskExecutor.setThreadFactory(new NamedThreadFactory(threadName, true));
        //初始化线程池
        taskExecutor.initialize();
        return taskExecutor;
    }


    public static AsyncTaskExecutor getAsyncExecutor() {
        int coreSize = Runtime.getRuntime().availableProcessors();
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程数（默认线程数）
        executor.setCorePoolSize(coreSize);
        // 最大线程数
        executor.setMaxPoolSize(20);
        // 缓冲队列数
        executor.setQueueCapacity(200);
        // 允许线程空闲时间（单位：默认为秒）
        executor.setKeepAliveSeconds(60);
        // 线程池名前缀
        executor.setThreadNamePrefix("asyncExecutor-");
        // 设置是否等待计划任务在关闭时完成
        executor.setWaitForTasksToCompleteOnShutdown(true);
        // 设置此执行器应该阻止的最大秒数
        executor.setAwaitTerminationSeconds(60);
        // 线程池对拒绝任务的处理策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 初始化
        executor.initialize();
        return executor;
    }
}
